<template>
  <div
    v-for="(item, index) in specs"
    class="specs"
    :key="index"
  >
    <el-button
      type="danger"
      size="large"
      class="del"
      :icon="Delete"
      circle
      :disabled="disabled"
      @click="del(index)"
    />
    <SpecTag
      v-model="item.option"
      :title="item.title"
      :disabled="disabled"
    ></SpecTag>
  </div>
  <el-input
    v-if="inpVisible"
    ref="InputRef"
    class="add-spec inp"
    v-model="inputValue"
    size="large"
    @keyup.enter="addSpecs"
    @blur="addSpecs"
    :disabled="disabled"
  />
  <el-button
    v-else
    type="primary"
    @click="showInp"
    size="large"
    class="add-spec"
    :disabled="disabled"
    >添加规格</el-button
  >
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import { Delete } from "@element-plus/icons-vue";
import SpecTag from "@/components/Tag/SpecTag.vue";

// 规格
const specs = ref([]);

const inpVisible = ref(false);
const inputValue = ref("");
const InputRef = ref(null);
// 书写规格
function showInp() {
  inpVisible.value = true;
  nextTick(() => {
    InputRef.value.focus();
  });
}

// 新增
function addSpecs() {
  const notOnly = specs.value.some(
    (res) => res.title === inputValue.value
  );
  if (notOnly) {
    ElMessage.error("规格已存在");
    return;
  }
  if (inputValue.value.length === 0) {
    inputValue.value = "";
    inpVisible.value = false;
    return;
  }
  inpVisible.value = false;
  specs.value.push({
    title: inputValue.value,
    option: []
  });
  inputValue.value = "";
  emit("update:modelValue", specs.value);
}

// 删除
function del(ind) {
  specs.value = specs.value.filter((_res, index) => {
    return index !== ind;
  });
  emit("update:modelValue", specs.value);
}

const props = defineProps({
  modelValue: {
    default: []
  },
  disabled: {
    default: false
  }
});

const emit = defineEmits(["update:modelValue"]);

onMounted(() => {
  specs.value = props.modelValue;
});

watch(
  () => props.modelValue,
  (val) => {
    specs.value = val;
  },
  {
    deep: true
  }
);
</script>

<style lang="scss" scoped>
.specs {
  display: flex;
  align-items: center;
  .del {
    margin-right: 10px;
  }
}
.inp {
  width: 80px;
}

.add-spec {
  margin: 5px 0;
  margin-bottom: 15px;
  font-size: 20px;
}
</style>
